
import React from 'react';
import {Button, Card, Divider, Flex} from "antd";
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Upload } from 'antd';
import {testDownloadFileUsingGet, testUploadFileUsingPost} from "@/services/backend/fileController";
import {COS_HOST} from "@/constants";
import {saveAs} from "file-saver";



const TestFilePage: React.FC = () => {
  const [value, setValue] = React.useState<string>();
  const { Dragger } = Upload;
  const props: UploadProps = {
    name: 'file',
    multiple: false,
    maxCount:1,
    customRequest: async (fileObj:any) => {
      try {
        const res= await testUploadFileUsingPost({}, fileObj.file);
        fileObj.onSuccess(res.data);
        setValue(res.data);
        message.success('上传成功');
      }catch (e) {
        message.error('上传失败');
        fileObj.onError(e);
      }
    },
    onRemove: (file:any) => {
      setValue(undefined);
    }
  };

  return (
    <>
      <Flex gap={16}>
        <Card title="文件上传">
          <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">Click or drag file to this area to upload</p>
            <p className="ant-upload-hint">
              Support for a single or bulk upload. Strictly prohibit from uploading company data or other
              band files
            </p>
          </Dragger>
        </Card>
        <Card title="文件下载">
          <div>文件地址：{COS_HOST+value}</div>
          <Divider/>
          <img src={COS_HOST+value} alt={COS_HOST+value} height={200} />
          <Divider/>
          <Button
            onClick={ async () => {
              const blob =await testDownloadFileUsingGet({
                filepath:value
              },{
                responseType:"blob"
              });
              const fullPath=COS_HOST+value;
              saveAs(blob, fullPath.substring(fullPath.lastIndexOf('/') + 1));
            }
          }
          >点击下载文件</Button>
        </Card>
      </Flex>
    </>
  );
};
export default TestFilePage;
